<template>
  <view class="silent-login-container">
    <!-- 静默登录提示条 -->
    <view v-if="!isLoggedIn && showLoginTip && ttAvailable" class="login-tip">
      <view class="tip-content">
        <view class="tip-icon">
          <uni-icons type="person-filled" size="20" color="#ff6b6b"></uni-icons>
        </view>
        <view class="tip-text">
          <text class="tip-title">授权登录</text>
          <text class="tip-desc">获取您的抖音账号信息，提供更好的服务体验</text>
        </view>
        <view class="tip-actions">
          <button class="tip-btn cancel-btn" @click="hideLoginTip">暂不登录</button>
          <!-- 改为直接调用登录，不再依赖 getUserInfo 以避免隐私协议报错 -->
          <button 
            class="tip-btn login-btn" 
            @click="handleLogin"
            :loading="isLoggingIn"
          >
            {{ isLoggingIn ? '登录中...' : '一键登录' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 登录成功提示 -->
    <view v-if="isLoggedIn && showSuccessTip && ttAvailable" class="success-tip">
      <view class="success-content">
        <view class="success-icon">
          <uni-icons type="checkmarkempty" size="20" color="#52c41a"></uni-icons>
        </view>
        <view class="user-info" v-if="userInfo">
          <image v-if="userInfo.avatarUrl" :src="userInfo.avatarUrl" class="user-avatar" mode="aspectFill"></image>
          <text class="success-text">{{ userInfo.nickName || '登录成功' }}</text>
        </view>
        <text v-else class="success-text">登录成功</text>
        <view class="success-close" @click="hideSuccessTip">
          <uni-icons type="close" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { loginController } from '../utils/login.js';
import { useUserStore } from '../stores/user.js';

export default {
  name: 'SilentLogin',
  props: {
    // 是否自动静默登录
    autoLogin: {
      type: Boolean,
      default: true
    },
    // 是否优先展示授权弹条，不走静默登录
    preferPrompt: {
      type: Boolean,
      default: true
    },
    // 延迟显示登录提示的时间（毫秒）
    delayShow: {
      type: Number,
      default: 1000
    }
  },
  setup() {
    const userStore = useUserStore();
    
    return {
      userStore
    };
  },
  data() {
    return {
      showLoginTip: false,
      showSuccessTip: false,
      ttAvailable: typeof tt !== 'undefined',
      suppressKey: 'suppressLoginPrompt'
    };
  },
  computed: {
    isLoggedIn() {
      return this.userStore.isLoggedIn;
    },
    isLoggingIn() {
      return this.userStore.isLoading;
    },
    userInfo() {
      return this.userStore.userInfo;
    }
  },
  mounted() {
    this.initLogin();
    // 监听来自 App 的触发事件
    try {
      if (typeof uni !== 'undefined' && uni.$on) {
        uni.$on('triggerSilentLogin', () => {
          this.initLogin();
        });
        uni.$on('appHide', () => {
          // 退出小程序时清除登录状态，下次进入需要重新登录
          this.userStore.logout();
          this.showLoginTip = false;
          this.showSuccessTip = false;
        });
      }
    } catch (e) {}
  },
  methods: {
    /**
     * 处理获取用户信息
     */
    async handleGetUserInfo(res) {
      console.log('获取用户信息结果:', res);
      const { userInfo, errMsg } = res.detail;
      
      if (errMsg === 'getUserInfo:ok' && userInfo) {
        // 用户同意授权，获取到用户信息
        this.userInfo = userInfo;
        console.log('获取到用户信息:', userInfo);
        
        // 保存用户信息到本地存储
        if (typeof tt !== 'undefined') {
          tt.setStorageSync('userInfo', userInfo);
        }
        
        // 执行登录流程
        await this.handleLogin();
      } else if (errMsg === 'getUserInfo:fail auth deny') {
        // 用户拒绝授权
        console.log('用户拒绝授权获取用户信息');
        uni.showToast({
          title: '需要授权才能使用完整功能',
          icon: 'none',
          duration: 2000
        });
      } else if (errMsg === 'getUserInfo:fail not login') {
        // 用户未登录
        console.log('用户未登录');
        uni.showToast({
          title: '请先登录抖音账号',
          icon: 'none',
          duration: 2000
        });
      } else {
        // 其他错误
        console.error('获取用户信息失败:', errMsg);
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'error',
          duration: 2000
        });
      }
    },

    /**
     * 初始化登录
     */
    async initLogin() {
      try {
        // 检查是否在抖音小程序环境中
        if (!this.ttAvailable) {
          console.log('不在抖音小程序环境中，使用模拟登录');
          // 在H5环境中，设置一个模拟的登录状态
          await this.userStore.login({
            userInfo: {
              nickName: 'H5测试用户',
              avatarUrl: '/static/logo.png'
            },
            userId: 1001,
            openid: 'h5_mock_openid',
            token: 'h5_mock_token'
          });
          this.$emit('login-success', {
            userId: 1001, // 模拟用户ID
            openid: 'h5_mock_openid',
            token: 'h5_mock_token',
            userInfo: this.userInfo
          });
          return;
        }

        // 尝试从本地存储获取用户信息
        try {
          const savedUserInfo = tt.getStorageSync('userInfo');
          if (savedUserInfo) {
            this.userInfo = savedUserInfo;
          }
        } catch (e) {
          console.log('本地没有保存的用户信息');
        }

        // 如果设置了不再打扰（直到手动清缓存），则不展示弹框
        try {
          const suppressed = this.ttAvailable ? tt.getStorageSync(this.suppressKey) : (typeof uni !== 'undefined' ? uni.getStorageSync(this.suppressKey) : '')
          if (suppressed) {
            // 已被用户选择“暂不打扰”，直接退出
            return;
          }
        } catch (e) {}

        // 先检查本地登录状态（有 token 不应展示弹框）
        if (this.userStore.checkLoginStatus()) {
          // 已登录：仅在首次从未登录切换到已登录时触发回调，避免页面切换时重复触发
          if (!this.isLoggedIn) {
            this.$emit('login-success', {
              userId: this.userStore.userId,
              openid: this.userStore.openid,
              token: this.userStore.token,
              userInfo: this.userInfo
            });
          }
          return;
        }

        // 未登录时：若优先展示授权提示，直接展示
        if (this.preferPrompt) {
          console.log('[SilentLogin] 未登录，按 preferPrompt 显示授权条');
          this.showLoginTip = true;
          return;
        }

        // 如果自动登录，尝试静默登录
        if (this.autoLogin) {
          const success = await loginController.silentLogin();
          if (success) {
            // 使用Pinia更新登录状态
            await this.userStore.login({
              userInfo: this.userInfo,
              token: loginController.getToken(),
              userId: loginController.getUserId(),
              openid: loginController.getOpenid()
            });
            this.showSuccessTip = true;
            this.$emit('login-success', {
              userId: this.userStore.userId,
              openid: this.userStore.openid,
              token: this.userStore.token,
              userInfo: this.userInfo
            });
            return;
          }
        }

        // 尚未登录：延迟显示
        setTimeout(() => {
          if (!this.userStore.isLoggedIn) {
            this.showLoginTip = true;
          }
        }, this.delayShow);

      } catch (error) {
        console.error('初始化登录失败:', error);
        // 延迟显示登录提示
        setTimeout(() => {
          if (!this.userStore.isLoggedIn) {
            this.showLoginTip = true;
          }
        }, this.delayShow);
      }
    },

    /**
     * 处理登录
     */
    async handleLogin() {
      if (this.isLoggingIn) return;
      
      // 检查是否在抖音小程序环境中
      if (typeof tt === 'undefined') {
        console.log('不在抖音小程序环境中，无法执行登录');
        uni.showToast({
          title: '当前环境不支持登录',
          icon: 'none'
        });
        return;
      }
      
      try {
        const success = await loginController.login(true);
        
        if (success) {
          // 使用Pinia更新用户状态
          await this.userStore.login({
            userInfo: this.userInfo,
            token: loginController.getToken(),
            userId: loginController.getUserId(),
            openid: loginController.getOpenid()
          });
          
          this.showLoginTip = false;
          this.showSuccessTip = true;
          
          this.$emit('login-success', {
            userId: this.userStore.userId,
            openid: this.userStore.openid,
            token: this.userStore.token,
            userInfo: this.userInfo
          });
          
          // 3秒后自动隐藏成功提示
          setTimeout(() => {
            this.hideSuccessTip();
          }, 3000);
        }
      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'error'
        });
      }
    },

    /**
     * 隐藏登录提示
     */
    hideLoginTip() {
      this.showLoginTip = false;
      // 记忆用户选择：不再打扰，直到手动清除缓存
      try {
        if (this.ttAvailable) {
          tt.setStorageSync(this.suppressKey, 1)
        } else if (typeof uni !== 'undefined') {
          uni.setStorageSync(this.suppressKey, 1)
        }
      } catch (e) {}
      this.$emit('login-cancel');
    },

    /**
     * 隐藏成功提示
     */
    hideSuccessTip() {
      this.showSuccessTip = false;
    },

    /**
     * 打开授权提示（供外部主动拉起）
     */
    openPrompt() {
      this.showLoginTip = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.silent-login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9999;
  pointer-events: none;
}

.login-tip {
  /* 穆夏风：温暖金色系+毛玻璃边框 */
  background: linear-gradient(135deg, rgba(244, 228, 188, 0.9), rgba(245, 242, 237, 0.9));
  color: #8b4513;
  padding: 16px 18px;
  pointer-events: auto;
  box-shadow: 0 8px 24px rgba(212, 175, 55, 0.18);
  border: 1px solid rgba(212, 175, 55, 0.35);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  
  .tip-content {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .tip-icon { flex-shrink: 0; }
  
  .tip-text {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    .tip-title { font-size: 18px; font-weight: 700; font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif; color: #8b4513; }
    
    .tip-desc { font-size: 12px; opacity: 0.9; line-height: 1.4; color:#7a6a55; font-family:'PingFang SC', 'Microsoft YaHei', sans-serif; }
  }
  
  .tip-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
    
    .tip-btn { padding: 8px 16px; border-radius: 20px; font-size: 14px; border: none; cursor: pointer; transition: all 0.3s ease; }
    .cancel-btn { background: rgba(212, 175, 55, 0.12); color: #8b4513; }
    .cancel-btn:active { transform: scale(0.98); }
    .login-btn { background: linear-gradient(135deg, #d4af37, #f4e4bc); color: #8b4513; box-shadow: 0 4px 12px rgba(212, 175, 55, 0.3); }
    .login-btn:active { transform: translateY(1px); box-shadow: 0 2px 8px rgba(212, 175, 55, 0.4); }
  }
}

.success-tip {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
  margin: 10px;
  padding: 12px 16px;
  pointer-events: auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .success-content {
    display: flex;
    align-items: center;
    gap: 12px;
    position: relative;
  }
  
  .success-icon {
    flex-shrink: 0;
  }
  
  .user-info {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8px;
    
    .user-avatar {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      border: 2px solid #52c41a;
    }
    
    .success-text {
      font-size: 14px;
      color: #52c41a;
      font-weight: 500;
    }
  }
  
  .success-text {
    flex: 1;
    font-size: 14px;
    color: #52c41a;
    font-weight: 500;
  }
  
  .success-close {
    flex-shrink: 0;
    padding: 4px;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.3s ease;
    
    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
  }
}
</style>
